package com.tronsis.distribution.activity.me.address;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tronsis.distribution.R;
import com.tronsis.distribution.SysApplication;
import com.tronsis.distribution.bean.AddressBean;
import com.tronsis.distribution.bean.RegionBean;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.widget.address.BottomDialog;
import com.tronsis.distribution.widget.address.OnAddressSelectedListener;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.KeyboardUtils;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddressEditActivity extends ToolBarBaseActivity {

    @BindView(R.id.tv_address_area)
    TextView mTvArea;
    @BindView(R.id.tv_province)
    TextView mTvProvince;
    @BindView(R.id.ll_address_detail)
    LinearLayout mLlAddressDetail;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.ll_address)
    LinearLayout mLlAddress;
    @BindView(R.id.et_detail)
    EditText mEtDetail;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    AddressBean mAddressBean;

    private PopupWindow mProvincePopupWindow;
    private List<RegionBean> mRegionBeanList;

    private RegionBean mProvinceRegionBean;
    private String mRegionCode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_edit);
        ButterKnife.bind(this);

        mRegionBeanList = SysApplication.getRegionList();

        Intent intent = getIntent();
        String intentType = intent.getType();
        mAddressBean = (AddressBean) intent.getSerializableExtra("editAddressBean");
        if (null != mAddressBean) {
            mEtName.setText(mAddressBean.getName());
            mEtPhone.setText(mAddressBean.getPhone());
            String region = mAddressBean.getRegion();
            mRegionCode = mAddressBean.getRegion();
            if (region != null) {
                String provinceCode = region.substring(0, 2);
                mProvinceRegionBean = CommonUtil.getProvinceRegion(provinceCode);
                if (mProvinceRegionBean != null) {
                    mTvProvince.setText(mProvinceRegionBean.getName());
                }
                mTvArea.setText(CommonUtil.getCityRegionString(region));
            }
            mEtDetail.setText(mAddressBean.getDetail());
        }
        if (StringUtil.isEquals(intentType, "add")) {
            setTitle(true, getString(R.string.add_new_address));
        } else if (StringUtil.isEquals(intentType, "edit")) {
            setTitle(true, getString(R.string.edit_address));
        }

    }

    @OnClick(R.id.btn_confirm)
    void confirmClick() {
        String detail = mEtDetail.getText().toString();
        String name = mEtName.getText().toString();
        String phone = mEtPhone.getText().toString();
        String province = mTvProvince.getText().toString();
        String region = mTvArea.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showMessage(mContext, "请输入姓名");
            return;
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showMessage(mContext, "请输入手机号");
            return;
        }
        if (!StringUtil.isMobile(phone)) {
            ToastUtil.showMessage(mContext, "请输入正确的手机号");
            return;
        }

        if (TextUtils.isEmpty(province)) {
            ToastUtil.showMessage(mContext, "请输入所属省份");
            return;
        }

        if (TextUtils.isEmpty(region)) {
            ToastUtil.showMessage(mContext, "请输入所属城市");
            return;
        }


        if (TextUtils.isEmpty(detail)) {
            ToastUtil.showMessage(mContext, "请输入详细地址");
            return;
        }


        if (null == mAddressBean) {
            addAddress(detail, name, phone, mRegionCode);
        } else {
            updateAddress(mAddressBean.getId(), detail, name, phone, mRegionCode);
        }
    }


    @OnClick(R.id.ll_province)
    public void provinceClick() {
        KeyboardUtils.hideSoftInput(this);
//        showRegionPopupWindow();

        final RegionBean regionBean = new RegionBean();
        regionBean.setChildren(mRegionBeanList);
        final BottomDialog dialog = new BottomDialog(this, regionBean, 1);
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                String s = (province == null ? "" : "" + province.getName()) + (city == null ? "" : "" + city.getName());

                if (mProvinceRegionBean != null && !mProvinceRegionBean.getCode().equals(province.getCode())) {
                    mTvArea.setText(null);
                }
                mProvinceRegionBean = province;
                mTvProvince.setText(mProvinceRegionBean.getName());

                dialog.dismiss();


            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 弹出地区选择框
     */
    @OnClick(R.id.ll_address)
    public void addressClick() {
        KeyboardUtils.hideSoftInput(this);
        if (mProvinceRegionBean == null) {
            ToastUtil.showMessage(this, "请先选择所属省份");
            return;
        }

        final BottomDialog dialog = new BottomDialog(this, mProvinceRegionBean, 2);
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                //(province == null ? "" : province.getName()) +
                String s = (province == null ? "" : "" + province.getName()) + (city == null ? "" : "" + city.getName());
                mTvArea.setText(s);
                if (city != null && city.getCode() != null) {
                    if (city.getCode().length() > 5) {
                        mRegionCode = city.getCode().substring(0, 6);
                    } else {
                        mRegionCode = city.getCode();
                    }
                }
                dialog.dismiss();
            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


    private void showRegionPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_region_list, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mProvincePopupWindow == null) {
            mProvincePopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mProvincePopupWindow.setFocusable(true);
            mProvincePopupWindow.setOutsideTouchable(true);
            /* mProvincePopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mProvincePopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mProvincePopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mProvincePopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mProvincePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(AddressEditActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mProvincePopupWindow.dismiss();
                }
            });


            RecyclerView rv = view.findViewById(R.id.rv_type);
            CommonAdapter<RegionBean> adapter = new CommonAdapter<RegionBean>(mContext, mRegionBeanList, R.layout.item_resource_type) {
                @Override
                protected void convert(ViewHolder holder, RegionBean s, int position) {
                    holder.setText(R.id.tv_type, s.getName());
                }
            };
            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    mProvincePopupWindow.dismiss();
                    RegionBean province = mRegionBeanList.get(position);
                    if (mProvinceRegionBean != null && !mProvinceRegionBean.getCode().equals(province.getCode())) {
                        mTvArea.setText(null);
                    }
                    mProvinceRegionBean = province;
                    mTvProvince.setText(mProvinceRegionBean.getName());

                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });
            int height = DisplayUtil.getInstance(mContext).dp2px(1);
            int color = Color.parseColor("#F4F4F4");
            RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
            rv.addItemDecoration(decoration);
            rv.setLayoutManager(new LinearLayoutManager(this));
            rv.setAdapter(adapter);

        }
        WindowUtil.setPopWindowBackgroundAlpha(AddressEditActivity.this, 0.7f);
        mProvincePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void updateAddress(final String addrId, final String detail, final String name, final String phone, final String region) {
        try {
            UserBizFactory.createBiz().updateAddress(this, addrId, detail, name, phone, region, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    setResult(Activity.RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void addAddress(final String detail, final String name, final String phone, final String region) {
        try {
            UserBizFactory.createBiz().addAddress(this, detail, name, phone, region, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    setResult(Activity.RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

}
